package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.WordDao;
import com.ezjie.ielts.db.WordInstanceDao;
import com.ezjie.ielts.db.WordMeaningDao;
import com.ezjie.ielts.db.WordQuestionDao;
import com.ezjie.ielts.model.ReviewWordData;
import com.ezjie.ielts.model.WordGroup;
import com.ezjie.ielts.model.WordGroupBean;
import com.ezjie.ielts.model.WordGroupResponse;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.PreferencesUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.view.MyWordsView;
import com.ezjie.ielts.view.ProgressCircle;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

public class ReviewContentFragment extends Fragment implements OnClickListener {

	private Context mContext;
	private Button startLearn;// 开始学习
	private TextView finishNum, vocabularyNum, groupNum, progress_day;// 完成数，词汇数,第几组
	private WordGroup mGroup;
	private ArrayList<WordGroup> content;
	private List<WordGroup> mGroups;
	private int pos;
	private int isReview;
	private boolean isFinish = false;// 判断是不是查看详情
	private ScrollView viewpager_sv;

	private ProgressCircle seekCircle;
	private Handler handler = new Handler();
	private int progress = 0;
	private ProgressDialog mProgressDialog;
	private WordGroupBean mGroupBean;

	private MyWordsView myWordsView;// 弾幕
	private List<String> keywords = new ArrayList<String>();
	private WordDao dao;
	private WordInstanceDao instanceDao;
	private WordMeaningDao meaningDao;
	private WordQuestionDao questionDao;
	private WordTask mWordTask;

	public static Fragment newInstance(int postion, ArrayList<WordGroup> content, int isReview) {
		ReviewContentFragment fragment = new ReviewContentFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("pos", postion);
		bundle.putInt("isReview", isReview);
		bundle.putParcelableArrayList("content", content);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(null);
		mContext = getActivity();
		mGroups = new ArrayList<WordGroup>();
		dao = new WordDao(mContext);
		instanceDao = new WordInstanceDao(mContext);
		meaningDao = new WordMeaningDao(mContext);
		questionDao = new WordQuestionDao(mContext);
		mWordTask = new WordTask(mContext);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mProgressDialog != null && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.review_viewpager_content, null);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		setView();
	}

	private Handler handler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (keywords.size() >= 4) {
					myWordsView.show(keywords);
				}
				break;
			}

		}
	};

	Runnable r = new Runnable() {
		@Override
		public void run() {
			progress += 1;
			if (progress <= mGroup.getStatus()) {
				seekCircle.setProgress((progress) - 1);
				handler.postDelayed(r, 250);
			} else {
				handler.removeCallbacks(r);
			}

		}
	};

	private void setView() {
		progress_day.setText(R.string.reviewed);
		if (0 == isReview) {
			setReviewData();
		} else if (1 == isReview) {
			setStrengthenData();
		}
		myWordsView.setKeywords(keywords);
		myWordsView.setDuration(5000);
		handler2.sendEmptyMessage(1);
		handler.post(r);
	}

	// 添加强化数据
	private void setStrengthenData() {
		if (0 == mGroup.getTemp_status()) {
			isFinish = false;
			startLearn.setText(R.string.start_strengthen);
			viewpager_sv.setBackgroundResource(R.drawable.dds);
		} else if (1 == mGroup.getTemp_status()) {
			isFinish = false;
			startLearn.setText(R.string.go_strengthen);
			viewpager_sv.setBackgroundResource(R.drawable.ing);
		} else if (2 == mGroup.getTemp_status()) {
			isFinish = true;
			startLearn.setText(R.string.see_details);
			viewpager_sv.setBackgroundResource(R.drawable.finished);
		}
		startLearn.setOnClickListener(this);
		if (0 == mGroup.getPassed()) {
			finishNum.setVisibility(View.INVISIBLE);
		} else {
			finishNum.setVisibility(View.VISIBLE);
			String finishString = String.format(getResources().getString(R.string.review_finish_num),
					mGroup.getPassed() + "");
			SpannableStringBuilder style = new SpannableStringBuilder(finishString);
			style.setSpan(new ForegroundColorSpan(Color.parseColor("#DDDDDD")), 0, 3,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			finishNum.setText(style);
		}
		String vocabularyString = String.format(getResources().getString(R.string.vocabulary_num), mGroup.getTotal()
				+ "");
		SpannableStringBuilder style = new SpannableStringBuilder(vocabularyString);
		style.setSpan(new ForegroundColorSpan(Color.parseColor("#DDDDDD")), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		vocabularyNum.setText(style);
		groupNum.setText(String.format(getResources().getString(R.string.group_num), (pos + 1) + ""));
	}

	// 添加复习数据
	public void setReviewData() {
		if (0 == mGroup.getTemp_status()) {
			isFinish = false;
			startLearn.setText(R.string.start_learn);
			viewpager_sv.setBackgroundResource(R.drawable.dds);
		} else if (1 == mGroup.getTemp_status()) {
			isFinish = false;
			startLearn.setText(R.string.go_learn);
			viewpager_sv.setBackgroundResource(R.drawable.ing);
		} else if (2 == mGroup.getTemp_status()) {
			isFinish = true;
			startLearn.setText(R.string.see_details);
			viewpager_sv.setBackgroundResource(R.drawable.finished);
		}
		startLearn.setOnClickListener(this);
		// handler.post(r);
		if (0 == mGroup.getPassed()) {
			finishNum.setVisibility(View.INVISIBLE);
		} else {
			finishNum.setVisibility(View.VISIBLE);
			String finishString = String.format(getResources().getString(R.string.review_finish_num),
					mGroup.getPassed() + "");
			SpannableStringBuilder style = new SpannableStringBuilder(finishString);
			style.setSpan(new ForegroundColorSpan(Color.parseColor("#DDDDDD")), 0, 3,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			finishNum.setText(style);
		}
		String vocabularyString = String.format(getResources().getString(R.string.vocabulary_num), mGroup.getTotal()
				+ "");
		SpannableStringBuilder style = new SpannableStringBuilder(vocabularyString);
		style.setSpan(new ForegroundColorSpan(Color.parseColor("#DDDDDD")), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		vocabularyNum.setText(style);
		groupNum.setText(String.format(getResources().getString(R.string.group_num), (pos + 1) + ""));
	}

	private void initView(View view) {
		myWordsView = (MyWordsView) view.findViewById(R.id.animword);
		seekCircle = (ProgressCircle) view.findViewById(R.id.review_progress);
		seekCircle.setMax(6);
		viewpager_sv = (ScrollView) view.findViewById(R.id.viewpager_sv);
		startLearn = (Button) view.findViewById(R.id.start_learn);
		progress_day = (TextView) view.findViewById(R.id.progress_day);
		finishNum = (TextView) view.findViewById(R.id.finish_num);
		vocabularyNum = (TextView) view.findViewById(R.id.vocabulary_num);
		groupNum = (TextView) view.findViewById(R.id.group_num);
		content = getArguments().getParcelableArrayList("content");
		pos = getArguments().getInt("pos");
		isReview = getArguments().getInt("isReview");
		mGroup = content.get(pos);
		keywords = mGroup.getWord_list();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_REVIEW_CONTENT);
		MobclickAgent.onResume(mContext);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_REVIEW_CONTENT);
		MobclickAgent.onPause(mContext);
	}

	/*
	 * @Override public void setUserVisibleHint(boolean isVisibleToUser) {
	 * 
	 * if (isVisibleToUser) {
	 * 
	 * } super.setUserVisibleHint(isVisibleToUser); }
	 */

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_learn:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "word_start_reviewBtn");
			if (mContext != null) {
				if (isFinish) {
					getWordGroup(mGroup.getWgid() + "");
				} else {
					YsApplication myApplication = (YsApplication) getActivity().getApplication();
					ReviewWordData data = new ReviewWordData(mGroup.getWgid(), isFinish, isReview);
					myApplication.setReviewWordData(data);
					Intent intent = new Intent(mContext, ReviewStudyManagerActivity.class);
					startActivity(intent);

					for (int i = 0; i < content.size(); i++) {
						if (content.get(i).getTemp_status() != 2) {
							mGroups.add(content.get(i));
						}
					}

					if (mGroups != null && mGroups.size() > 0) {
						for (int j = 0; j < mGroups.size(); j++) {
							if (mGroups.get(j).getWgid() == mGroup.getWgid()) {
								if (j < mGroups.size() - 1) {
									PreferencesUtil.putInt(mContext, "status", mGroups.get(j + 1).getStatus());
									PreferencesUtil.putInt(mContext, "nextWgid", mGroups.get(j + 1).getWgid());
								} else {
									PreferencesUtil.putInt(mContext, "status", mGroups.get(j).getStatus());
									PreferencesUtil.putInt(mContext, "nextWgid", -1);
								}
							}
						}
					} else {
						PreferencesUtil.putInt(mContext, "nextWgid", -1);
					}
				}
			}
			break;
		}
	}

	// 获取单词组
	private void getWordGroup(String wgid) {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}
		mWordTask.getWordGroup(wgid, "simple", new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(getActivity());
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					WordGroupResponse mGroupResponse = JSON.parseObject(result, WordGroupResponse.class);
					if (mGroupResponse != null && 200 == mGroupResponse.getStatus_code()) {
						String mGroupBeanStr = mGroupResponse.getData();
						if (!TextUtils.isEmpty(mGroupBeanStr)) {
							mGroupBean = JSON.parseObject(mGroupBeanStr, WordGroupBean.class);
							YsApplication myApplication = (YsApplication) getActivity().getApplication();
							myApplication.setmGroupBean(mGroupBean);

							Intent intent = new Intent(mContext, ReviewFinishActivity.class);
							intent.putExtra("isFinish", isFinish);
							startActivity(intent);
						}
					} else {
						if (getActivity() != null) {
							AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
						}
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
			}
		});
	}

}
